
import { Message,Notification,MessageBox  } from 'element-ui';
import $https from '@/utils/https'
const getMessages = function () { }

const newConnect = (context: any, data: any) => {
  $https.post('/new-connect', data).then((resp: any) => {
    //
    console.log('返回结果：', resp)
    if (resp.data.code == 200) {
      // 新建成功
      // 1、把连接信息保存到state中
      let _connect = resp.data.data

      context.state.list.push(_connect)
      // 2、清空输入框、关闭抽屉
      context.rootState.ui.newConnaction.drawer = false

      Message({
        message: '连接成功',
        type: 'success'
      });
    } else {
      console.log('newConnect acion 失败..')
    }
  })
}


const closeConnect = (context: any, data: any) => {
  $https.post('/close-connect', data).then((resp: any) => {
    console.log('respxxx', resp)
    if (resp.data.code == 200) {
      // 关闭成功、修改state
      context.commit('updatelist', resp.data.data)
    } else {
      console.log('closeConnect acion 失败..')

    }
  })
}

const openConnect = (context: any, data: any) => {
  $https.post('/open-connect', data).then((resp: any) => {
    console.log('respxxx', resp)
    if (resp.data.code == 200) {
      // 关闭成功、修改state
      context.commit('updatelist', resp.data.data)
    } else {
      console.log('openConnect acion 失败..')

    }
  })
}

const removeConnect = (context: any, data: any) => {
  $https.post('/remove-connect', data).then((resp: any) => {
    console.log(resp)
    if (resp.data.code == 200) {
      // 关闭成功、修改state
      context.commit('removeconnect', { _id: data.connID })
    } else {
      console.log('removeConnect acion 失败..')

    }
  })
}

// 测试连接
const testConnect = (context: any, data: any)=>{
  $https.post('/test-connect', data).then(
        (resp:any) => {
          console.log('成功返回：', resp)

          if (resp.data.code == 200) {
            Message({
              message: `连接成功（版本：${resp.data.data.version}）`,
              type: 'success'
            })
          } else {
            Notification({
              title: `错误码: ${resp.data.data.errno}(${resp.data.data.sqlState})`,
              message: resp.data.data.sqlMessage,
              duration: 0 // 不会自动关闭
            })
          }// end else
        },
        (error:any) => {
          console.error('错误返回：', error)
          MessageBox(JSON.stringify(error), '错误');
        }
      )
}

export default {
  getMessages,
  closeConnect, openConnect, removeConnect, newConnect, testConnect
};
